﻿package com.sonishpere 
{
	import com.saint.utils.Logger;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Matrix;
	
	/**
	 * ...
	 * @author kembera
	 */
	public class Fizzler 
	{
		private var lineSpacing:Number = 4;
		private var lineHeight:Number = 1;
		private var hght:Number = 0;
		private var _target:Sprite;
		private var lineHolder:Sprite;
		private var skewAmount:Number;
		private var xOrigOffset:Number = -35;
		private var xOffset:Number;
		private var origX:Number;
		private var isFizzed:Boolean;
		private var fizzDone:Boolean = false;
		
		public function Fizzler(target:Sprite) 
		{
			Logger.info("Fizzler.Fizzler");
			_target = target;
			lineHolder = new Sprite();	
			_target.addChild(lineHolder);
			origX = _target.x;
		}
		
		public function startFizzle():void 
		{
					
			doFizzle();
			
		}
		
		public function doFizzle():void
		{
			Logger.info("/nFizzler.doFizzle isFizzed" + isFizzed);
			/* draw lines */
			if (!isFizzed)
			{
			
				isFizzed = true;
				lineHolder.graphics.moveTo(0, 0);			
				hght = 0;
				do {
					lineHolder.graphics.beginFill(0xffcc00, 1);
					lineHolder.graphics.drawRect(0, hght, _target.width, lineHeight); 
					lineHolder.graphics.endFill();
					hght += lineSpacing;
				}while (hght < _target.height);			
				
			
				_target.mask = lineHolder;
				
				skewAmount = (Math.random() * 400) + 100;
		
				xOffset = xOrigOffset;
				if (Math.random() > 0.5)
				{
					skewAmount *= ( -1);
					xOffset *= ( -1);
				}
				skewer(_target, skewAmount, 0);
				_target.x += xOffset;
				_target.addEventListener(Event.ENTER_FRAME, enterFrameFizzle,  false, 0 , true);
			}	
		}
		
		public function endFizzle():void
		{
			if (isFizzed)
			{
				resetFizzle();
				_target.removeEventListener(Event.ENTER_FRAME, enterFrameFizzle);
			}
		}
		
		private function resetFizzle()
		{
			lineHolder.graphics.clear();
			_target.mask = null;
			skewer(_target, -skewAmount, 0 ); 
			_target.x = origX;
			isFizzed = false;
			fizzDone = false;
			
		}
		
		
		private function enterFrameFizzle(e:Event):void
		{
			var endVar:Number = Math.random();
			//Logger.info("enterFrameFizzle " );
			
			if (isFizzed )
			{
				if (fizzDone)
				{
					if (endVar > 0.65)
					{
						endFizzle()
					}else {
						
					}
					
				}else {
					fizzDone = true;
				}
			}
		}
			
		// _x and _y are the skew in degrees
		private function skewer(target:DisplayObject, _x:Number, _y:Number):void
		{
			var mtx:Matrix = new Matrix();
			mtx.b = _y * Math.PI/180;
			mtx.c = _x * Math.PI/180;
			mtx.concat(target.transform.matrix);
			target.transform.matrix = mtx;
			
		
		}
		
	}
	
}